

local util_file = require("luastar.util.file")
----local logger=logger;

local Route = Class("com.ea.core.Route")

function Route:init(config_file)
    -- ngx.log(ngx.INFO, logger.formatMsg("[Route:init] file : ", config_file))
    self.config_file = config_file
    if not self.config_file then
        ngx.log(ngx.ERR, logger.formatMsg("[Route:init] illegal argument : config_file can't nil."))
        return
    end
    local config = util_file.loadlua(self.config_file)
    -- 初始化路由配置
    self.config_route = config["route"] or {}
    
    for i, val in ipairs(self.config_route) do
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("request uri %s ,url:  %s , class: %s , method: %s",uri,val["url"],val["class"],val["method"]))); end
         
        
    end
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Route:init] config_route : ", cjson.encode(self.config_route))) end
    -- 初始化拦截器配置
    self.config_interceptor = config["interceptor"] or {}
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg( "[Route:init] config_interceptor : ", cjson.encode(self.config_interceptor))) end
end



function Route:getRoute(uri)
    if _.isEmpty(uri) then
        ngx.log(ngx.ERR,logger.formatMsg( "[Route:getRoute] uri is nil."))
        return nil
    end
    
    for i, val in ipairs(self.config_route) do
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("request uri %s ,url:  %s , class: %s , method: %s",uri,val["url"],val["class"],val["method"]))); end
         
         if ngx.re.match(uri,val["url"]) then        
             if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg("find controller ",string.format("  class: %s , method: %s",val["class"],val["method"]))) ; end
            return { class = val["class"], method = val["method"] }
        end
    end
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Route:getRoute] no url find for uri :", uri)) end
    return nil
end

function Route:getInterceptor(uri)
  if _.isEmpty(uri) then
        ngx.log(ngx.ERR, logger.formatMsg("[Route:getRoute] uri is nil."))
        return nil
    end
    local interceptorAry = {}
    _.each(self.config_interceptor, function(i, val)
        local is, ie = string.find(uri, val["url"])
        if not is then
            return
        end
        if val["excludes"] and _.contains(val["excludes"], uri) then
            return
        end
        table.insert(interceptorAry, val["class"])
    end)
    return interceptorAry
end


return Route;